package cn.wenhaha.job;

import cn.hutool.core.util.StrUtil;
import cn.wenhaha.common.bean.AppInstallFinish;
import cn.wenhaha.common.bean.JobStartEvent;
import cn.wenhaha.common.config.GlobalApp;
import org.quartz.spi.JobFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.EventObject;
import java.util.Properties;

/**
 * 任务管理类
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-10-28 19:59
 */
@Component
public class QuartzJobManager implements DisposableBean {

    private static final Logger LOG = LoggerFactory.getLogger(QuartzJobManager.class);

    @Resource
    private SchedulerFactoryBean factoryBean;

    @Resource(name = "schedulerConfigProperties")
    private Properties properties;
    @Resource
    private DataSource dataSource;
    @Resource(name = "schedulerFactory")
    private JobFactory jobFactory;
    @Resource
    private ApplicationEventPublisher publisher;


    /**
     *  启动后，把需要运行的任务，重新加载到内存中
     */
    @EventListener({ApplicationReadyEvent.class, AppInstallFinish.class})
    @Order(20)
    public void startJob(EventObject event) throws Exception {
        if (GlobalApp.isLoadConfigDb() || event instanceof AppInstallFinish) {
            Integer type = GlobalApp.getGlobalApp().getType();
            if (StrUtil.equals("1",type.toString())){
                // 自定义查 启用
                properties.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS WHERE SCHED_NAME = {1} AND LOCK_NAME = ?");
            }
            initFactory();
            factoryBean.setQuartzProperties(properties);
            LOG.debug("正在开启调度任务");
            factoryBean.start();
            if (factoryBean.isRunning()){
                LOG.debug("开启调度任务成功");
                publisher.publishEvent(new JobStartEvent(factoryBean));
            }
        }else {
            LOG.debug("当前环境不能够开启调度任务");
        }
    }




    public void initFactory(){
        SchedulerFactoryBean factory = factoryBean;

        factory.setJobFactory(jobFactory);
        factory.setDataSource(dataSource);
        factory.setQuartzProperties(properties);
        // 延时启动
//        factory.setStartupDelay(5);
        factory.setApplicationContextSchedulerContextKey("applicationContextKey");
        // 可选，QuartzScheduler
        // 启动时更新己存在的Job，这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
        factory.setOverwriteExistingJobs(true);

        // 设置自动启动，默认为true
        factory.setAutoStartup(false);

    }


    @Override
    public void destroy() throws Exception {
        if (factoryBean!=null && factoryBean.isRunning()){
            LOG.debug("正在关闭定时任务");
            factoryBean.stop();
        }
    }
}
